package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        dowork(shardingContext.getShardingParameter());
    }

    private void dowork(String time) {
        //result有几种情况
        //第一种：如果调用服务挂掉了，直接走降级方法，返回值时null
        //第二种：调用服务出现异常，被统一异常处理到(code= ,msg= "")
        //第三种：正常返回（code=200,msg="操作成功",data=List<SeckillProductVo>）
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByTime(Integer.parseInt(time));
        //如果result正常返回
        if (result != null && !result.hasError()) {
            List<SeckillProductVo> list = result.getData();
            if (list != null && list.size() > 0) {
                for (SeckillProductVo vo : list) {
                    stringRedisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),String.valueOf(vo.getId()), JSON.toJSONString(vo));
                    stringRedisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),vo.getId()+"",vo.getStockCount()+"");
                }
            }
            System.err.println("同步成功"+time);
        }
    }
}
